package com.example.service;

import com.example.entity.Vehicle;
import com.example.entity.VehicleStatus;
import com.example.entity.OrderType;
import com.example.entity.VehicleType;
import com.example.repository.VehicleRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class VehicleService {
    private final VehicleRepository vehicleRepository;

    @Autowired
    public VehicleService(VehicleRepository vehicleRepository) {
        this.vehicleRepository = vehicleRepository;
    }

    @Cacheable(value = "vehicles", key = "#status.name()")
    public List<Vehicle> findByStatus(VehicleStatus status) {
        return vehicleRepository.findByStatus(status);
    }

    public List<Vehicle> getAvailableVehicles(OrderType type) {
        // 根据不同订单类型获取合适的车辆
        if (type == OrderType.IS_AUTONOMOUS) {
            // 对于自动驾驶订单，直接获取所有可用的自动驾驶车辆
            System.out.println("VehicleService类:从数据库寻找可用自动驾驶车辆");
            return vehicleRepository.findByIsAutonomousTrueAndStatus(VehicleStatus.AVAILABLE);
        } else {
            // 对于其他类型订单，获取非自动驾驶的匹配车辆
            System.out.println("VehicleService类:从数据库寻找可用非自动驾驶车辆");
            List<Vehicle> availableVehicles = findByStatus(VehicleStatus.AVAILABLE);
            // 根据订单类型过滤车辆
            return availableVehicles.stream()
                    .filter(v -> !v.isAutonomous()) // 排除自动驾驶车辆
                    .filter(v -> matchesVehicleType(v, type))
                    .collect(Collectors.toList());
        }
    }

    private boolean matchesVehicleType(Vehicle vehicle, OrderType type) {
        switch (type) {
            case ECONOMY:
                return vehicle.getType() == VehicleType.ECONOMY;
            case LUXURY:
                return vehicle.getType() == VehicleType.LUXURY;
            case CARPOOL:
                return vehicle.isCanCarpool();
            case IS_AUTONOMOUS:
                return vehicle.isAutonomous(); // 这个条件现在只用于备份检查
            default:
                return false;
        }
    }

    public void markVehicleONTRIP(Vehicle vehicle) {
        vehicle.setStatus(VehicleStatus.ON_TRIP);
        vehicleRepository.save(vehicle);
    }

    public void markVehicleAvailable(Vehicle vehicle) {
        vehicle.setStatus(VehicleStatus.AVAILABLE);
        vehicleRepository.save(vehicle);
    }
    
    /**
     * 获取所有车辆信息
     * @return 所有车辆列表
     */
    public List<Vehicle> getAllVehicles() {
        return vehicleRepository.findAll();
    }
    
    /**
     * 获取所有公司拥有的车辆
     * @return 公司拥有的车辆列表
     */
    public List<Vehicle> getCompanyOwnedVehicles() {
        return vehicleRepository.findAll().stream()
                .filter(Vehicle::isCompanyOwned)
                .collect(Collectors.toList());
    }
}